<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="cartInfo in cartInfoList" :key="cartInfo.id">
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" :checked='!!cartInfo.isChecked' @change="checkCartInfoState(cartInfo)">
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl">
            <div class="item-msg">{{ cartInfo.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{cartInfo.skuPrice}}</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="changeGoodsNum('decrement',cartInfo)">-</a>
            <input autocomplete="off" type="text" :value="cartInfo.skuNum" minnum="1" class="itxt" @change="changeGoodsNum('change',cartInfo,$event)">
            <a href="javascript:void(0)" class="plus"  @click="changeGoodsNum('increment',cartInfo)">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{cartInfo.skuPrice * cartInfo.skuNum}}</span>
          </li>
          <li class="cart-list-con7">
            <a href="javascript:;" class="sindelet" @click="showDialogByDeleteOne(cartInfo.skuId)">删除</a>
            <br>
            <a href="javascript:;">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll">
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click="showDialogBySelected">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择
          <span>{{selected}}</span>件商品</div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{totalMoney}}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade">结算</router-link>
        </div>
      </div>
    </div>

    <!-- 弹出框 -->
    <Dialog :show.sync='show' v-show="show">
      <template v-slot:header>
        提示
      </template>
      <template>
        将删除{{isDelOne ? '此件' : '这些'}}商品，是否继续？
      </template>
      <template #footer>
        <div class="btn-footer">
            <button @click="show=false" class="btn btn-cancel">取消</button>
            <button class="btn btn-primary" @click="delShopCartGoods">确定</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import { reqShopCartListData , reqUpdateShopCartListData , reqChangeAllCartState , reqDelOneShopCartGoods, reqDelManyShopCartGoods,reqAddOrUpdateCart} from '@/api'
import Dialog from '@/components/Dialog'
import { skuNumReg } from '@/utils/reg.js'

  export default {
    name: 'ShopCart',
    data() {
      return {
        cartInfoList:[],
        skuIdList:[], // 批量更新商品的选中状态数据
        show:false,
        isDelOne:false,
        skuId:0,
        leftCartInfoList:[],
        timeId:'',
        num:0
      }
    },
    async mounted() {
      // 获取购物车列表数据
      const res = await reqShopCartListData();
      if(res.code===200){
        this.cartInfoList = res.data[0].cartInfoList ? res.data[0].cartInfoList : ''
      }else{
        console.log(res.message);
      }
    },
    methods: {
      async checkCartInfoState(cartInfo){
        cartInfo.isChecked = 1-cartInfo.isChecked
        const res = await reqUpdateShopCartListData(cartInfo.skuId,cartInfo.isChecked);
        if(res.code === 200){
          alert("状态更新成功")
        }else{
          console.log(res.message);
        }
      },
      
      // 删除一条商品数据时显示的会话框
      showDialogByDeleteOne(skuId){
        this.show = true;
        this.skuId = skuId;
        this.isDelOne=true
      },

      // 点击批量删除弹出会话框
      showDialogBySelected(){
        this.show = true;
        this.isDelOne = false;
        // 清空原数据
        this.skuIdList = []
        // 获取删除商品的id
        this.cartInfoList.forEach(cartInfo=>{
          if(cartInfo.isChecked === 1){
            this.skuIdList.push(cartInfo.skuId)
          }else{
            this.leftCartInfoList.push(cartInfo)
          }
        })
      },

      // 删除商品数据
      async delShopCartGoods(){
        // 如果删除的是一条
        if(this.isDelOne){
          const res = await reqDelOneShopCartGoods(this.skuId)
            if(res.code === 200){
              // 关闭弹窗
              this.show = false
              // 重新渲染数据 过滤已删除的商品 返回新数组进行渲染 此法能少发送一次请求 提高性能
              this.cartInfoList = this.cartInfoList.filter(cartInfo=>cartInfo.skuId !== this.skuId)
            }else{
              console.log(res.message);
            }
            return
        }
        // 如果是批量删除
        const res = await reqDelManyShopCartGoods(this.skuIdList)
          if(res.code === 200){
            this.show = false
            // 
            this.cartInfoList = this.leftCartInfoList
          }else{
            console.log(res.message);
          }
      },

      // 改变商品数量
      async changeGoodsNum(type,cartInfo,e){
        let num = 0; // 发给服务器的差值 
        let { skuNum , skuId } = cartInfo
        if (type === 'increment') {
          if (cartInfo.skuNum < 200) {
            cartInfo.skuNum++
            num++
          }
        }else if(type === 'decrement'){
          // 商品数量大于1 才能减
          if (cartInfo.skuNum > 1) {
            cartInfo.skuNum--
            num--
          }
        }else{
          // 直接输入商品数量的情况
          // 拿到输入的数量
          let newSkuNum = e.target.value
          if (skuNumReg.test(newSkuNum)) {
              if (newSkuNum > 200) {
              num = 200 - cartInfo.skuNum;
              // 要记得更新页面的商品数量！不要只记得改服务器的数据！
              cartInfo.skuNum = newSkuNum
            }else{
              num = newSkuNum - cartInfo.skuNum
              cartInfo.skuNum = newSkuNum
            }
          } 
        }
        // if(num === 0 ) return
        // // 向服务器发送请求更新页面
        // const res = await reqAddOrUpdateCart(skuId,num)
        if(this.timeId) clearTimeout(this.timeId)
        this.timeId = setTimeout(async ()=>{
          if(this.num===0) return
          // 统一发送ajax请求
          const res  = await reqAddOrUpdateCart(skuId,num)
          if(res.code === 200){
            this.num = 0
            console.log('更改成功'); 
          }else{
            console.log('更改失败');
          }
        },500)
      }
    },
    computed:{
      // 1.实现全选全不选
      checkAll:{
        get(){
          /*思路：
                这个全选按钮是否选中，取决于每一项商品的选中状态
                如果有一个小按钮不被选中 则这个总按钮也不被选中 总按钮的checked是用ture和false控制的t
                every 返回的是布尔值
          */ 
          return this.cartInfoList.every(cartInfo=>cartInfo.isChecked===1)
        },
        async set(newVal){
          // 只要一更改 全选按钮 就执行
          this.cartInfoList.forEach(cartInfo => {
            // 如果新状态是true，就是1 不是true 就是0
            cartInfo.isChecked = newVal ? 1 : 0;

            // 把总按钮的状态赋给每一项商品的选中状态
            this.skuIdList.push(cartInfo.skuId);
          });
          // 统一批量更新选中状态
          const result = await reqChangeAllCartState(newVal ? 1 : 0,this.skuIdList );
          
          if (result.code === 200) {
              alert('更新成功')
          }else{
              alert(res.message)
          }
        }
      },

      // 2.统计选中的商品数
      selected(){
        return this.cartInfoList.reduce((prev,item)=>{
          // 因为ischecked状态只有 0，1 所以加上 ischecked 就行 
          return prev + item.isChecked
        },0)
      },

      // 3.总价
      totalMoney(){
        return this.cartInfoList.reduce((prev,item)=>{
          return prev + item.isChecked*item.skuPrice*item.skuNum
        },0)
      }
    },
    // 注册组件
    components:{Dialog}
  }

</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }
			

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
.btn-footer {
  position: absolute;
  right: 2px;
  bottom: 20px;
  .btn {
    width: 70px;
    height: 40px;
    border: none;
    border-radius: 6px;
    margin-right: 20px;
    cursor: pointer;
  }
  .btn-primary {
    color: #fff;
    background-color: #409eff;
    &:hover {
      background-color: #66b1ff;
    }
  }
  .btn-cancel {
    border: 1px solid #ccc;
    &:hover {
      background-color: #ecf5ff;
      color: #66b1ff;
    }
  }
}
</style>